package com.huantai.common.util.restemplate;

import com.huantai.common.exception.SystemException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate 工具类
 * 
 * @author Ma Chao
 * @version 2018年12月18日 上午11:30:12
 */

public class RestTemplateUtil {
    private RestTemplateUtil() {}

    public static String get(String url, RestTemplate restTemplate) {
        String result = null;
        try {
            result = restTemplate.getForEntity(url, String.class).getBody();
        } catch (RestClientException e) {
            throw new SystemException("get by restTemplate error " + e.getMessage());
        }
        return result;
    }

    public static String postJSON(String jsonStr, String url, RestTemplate restTemplate) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        String result = null;
        try {
            result = restTemplate.postForObject(url, entity, String.class);
        } catch (RestClientException e) {
            throw new SystemException("post by restTemplate error " + e.getMessage());
        }
        return result;
    }
}
